package com.example.OJ.compile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class CommandUtil {
    //1、通过Runtime类得到Runtime实例，指向exec方法
    //2、获取到标准输出，写入指定文件
    //3、获取到标准错误，写入指定文件
    //4、等待子进程结束，拿到子进程状态码
    public static int run(String cmd,String stdoutFile,String stderrFile){
        try{
            //1
            Process process = Runtime.getRuntime().exec(cmd);

            //2
            if(stdoutFile != null){
                InputStream stdoutFrom = process.getInputStream();
                FileOutputStream stdoutTo = new FileOutputStream(stdoutFile);
                while(true){
                    int ch = stdoutFrom.read();
                    if(ch == -1) break;
                    stdoutTo.write(ch);
                }

                stdoutFrom.close();
                stdoutTo.close();
            }

            //3
            if(stderrFile != null){
                InputStream stderrFrom = process.getErrorStream();
                FileOutputStream stderrTo = new FileOutputStream(stderrFile);
                while(true){
                    int ch = stderrFrom.read();
                    if(ch == -1) break;
                    stderrTo.write(ch);
                }

                stderrFrom.close();
                stderrTo.close();
            }

            //4
            int exitCode = process.waitFor();
            return exitCode;

        }catch (IOException e){
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 1;
    }
}
